from django.db import models
from django.contrib.auth.models import AbstractUser
from wechatpy.replies import TextReply, ImageReply, VideoReply, VoiceReply, EmptyReply, ArticlesReply


class OneBookUser(AbstractUser):
	SEX_MALE = 1
	SEX_FEMALE = 0
	SEX = (
		(SEX_FEMALE, '女',),
		(SEX_MALE, '男',),
	)

	openid = models.SlugField(max_length=32, default='', blank=True, verbose_name='OpenID')
	unionid = models.SlugField(max_length=32, unique=True, default='', blank=True, verbose_name='UnionID')
	remark = models.CharField(max_length=20, default='', blank=True, verbose_name='用户标签')

	nickname = models.CharField(max_length=20, verbose_name='昵称', default='', blank=True)
	sex = models.SmallIntegerField(choices=SEX, default=SEX_MALE, verbose_name='性别')
	city = models.CharField(max_length=20, verbose_name='城市', default='', blank=True)
	province = models.CharField(max_length=10, verbose_name='省份', default='', blank=True)
	headimgurl = models.URLField(verbose_name='用户头像', default='', blank=True)

	class Meta:
		verbose_name = '用户'
		verbose_name_plural = '用户'


class Content(models.Model):
	TEXT = 1
	IMAGE = 2
	AUDIO = 3
	VIDEO = 4
	CONTENT_TYPE = (
		(TEXT, '文本'),
		(IMAGE, '图片'),
		(AUDIO, '音频'),
		(VIDEO, '视频'),
	)

	name = models.CharField(max_length=20, verbose_name='名称')
	content = models.CharField(max_length=256, verbose_name='回复内容')
	content_type = models.SmallIntegerField(verbose_name='内容类型', choices=CONTENT_TYPE, default=TEXT)

	class Meta:
		verbose_name = verbose_name_plural = '消息内容'

	def __repr__(self):
		return '{}({})'.format(self.name, self.get_content_type_display())

	def __str__(self):
		return self.__repr__()

	def get_reply(self, msg):
		reply = EmptyReply()
		if self.content_type == self.TEXT:
			reply = TextReply(content=self.content, message=msg)
		elif self.content_type == self.IMAGE:
			reply = ImageReply(media_id=self.content, message=msg)
		elif self.content_type == self.AUDIO:
			reply = VoiceReply(media_id=self.content, message=msg)
		elif self.content_type == self.VIDEO:
			reply = VideoReply(media_id=self.content, message=msg)

		return reply


class WxAutoReply(models.Model):
	REPLY_ALL = 1
	REPLY_RANDOM = 0
	REPLY_TYPE = (
		(REPLY_RANDOM, '随机回复一条'),
		(REPLY_ALL, '全部回复'),
	)

	rule = models.CharField(max_length=20, unique=True, verbose_name='规则名称')
	keyword = models.CharField(max_length=20, unique=True, verbose_name='关键词')
	contents = models.ManyToManyField(Content, verbose_name='内容')
	reply_type = models.SmallIntegerField(verbose_name='回复方式', choices=REPLY_TYPE, default=REPLY_ALL)

	class Meta:
		verbose_name = verbose_name_plural = '自动回复'

	def __str__(self):
		return '{}/{}'.format(self.rule, self.keyword)
